home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Mac-Source 1994 July
/
Mac-Source_July_1994.iso
/
Other Langs
/
python
/
emacs-info
/
python-lib.info-3
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
Macintosh to JP
NeXTSTEP
RISC OS/Acorn
Shift JIS
UTF-8
Wrap
GNU Info File
|
1994-04-01
|
45.6 KB
|
1,081 lines
|
[
TEXT/R*ch
]
This is Info file python-lib.info, produced by Makeinfo-1.55 from the
input file lib.texi.
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system. It assumes basic
knowledge about the Python language. For an informal introduction to
the language, see the Python Tutorial. The Python Reference Manual
gives a more formal definition of the language. (These manuals are not
yet available in INFO or Texinfo format.)
Copyright (C) 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
File: python-lib.info, Node: posixpath, Next: pwd, Prev: posix, Up: UNIX ONLY
Standard Module `posixpath'
===========================
This module implements some useful functions on POSIX pathnames.
- function of module posixpath: basename (P)
Return the base name of pathname P. This is the second half of
the pair returned by `posixpath.split(P)'.
- function of module posixpath: commonprefix (LIST)
Return the longest string that is a prefix of all strings in LIST.
If LIST is empty, return the empty string (`''').
- function of module posixpath: exists (P)
Return true if P refers to an existing path.
- function of module posixpath: expanduser (P)
Return the argument with an initial component of `~' or `~USER'
replaced by that USER's home directory. An initial `~' is
replaced by the environment variable `$HOME'; an initial `~USER'
is looked up in the password directory through the built-in module
`pwd'. If the expansion fails, or if the path does not begin with
a tilde, the path is returned unchanged.
- function of module posixpath: isabs (P)
Return true if P is an absolute pathname (begins with a slash).
- function of module posixpath: isfile (P)
Return true if P is an existing regular file. This follows
symbolic links, so both islink() and isfile() can be true for the
same path.
- function of module posixpath: isdir (P)
Return true if P is an existing directory. This follows symbolic
links, so both islink() and isdir() can be true for the same path.
- function of module posixpath: islink (P)
Return true if P refers to a directory entry that is a symbolic
link. Always false if symbolic links are not supported.
- function of module posixpath: ismount (P)
Return true if P is a mount point. (This currently checks whether
`P/..' is on a different device from P or whether `P/..' and P
point to the same i-node on the same device -- is this test
correct for all UNIX and POSIX variants?)
- function of module posixpath: join (P, Q)
Join the paths P and Q intelligently: If Q is an absolute path,
the return value is Q. Otherwise, the concatenation of P and Q is
returned, with a slash (`'/'') inserted unless P is empty or ends
in a slash.
- function of module posixpath: normcase (P)
Normalize the case of a pathname. This returns the path unchanged;
however, a similar function in `macpath' converts upper case to
lower case.
- function of module posixpath: samefile (P, Q)
Return true if both pathname arguments refer to the same file or
directory (as indicated by device number and i-node number).
Raise an exception if a stat call on either pathname fails.
- function of module posixpath: split (P)
Split the pathname P in a pair `(HEAD, TAIL)', where TAIL is the
last pathname component and HEAD is everything leading up to that.
If P ends in a slash (except if it is the root), the trailing
slash is removed and the operation applied to the result;
otherwise, `join(HEAD, TAIL)' equals P. The TAIL part never
contains a slash. Some boundary cases: if P is the root, HEAD
equals P and TAIL is empty; if P is empty, both HEAD and TAIL are
empty; if P contains no slash, HEAD is empty and TAIL equals P.
- function of module posixpath: splitext (P)
Split the pathname P in a pair `(ROOT, EXT)' such that `ROOT + EXT
== P', the last component of ROOT contains no periods, and EXT is
empty or begins with a period.
- function of module posixpath: walk (P, VISIT, ARG)
Calls the function VISIT with arguments `(ARG, DIRNAME, NAMES)'
for each directory in the directory tree rooted at P (including P
itself, if it is a directory). The argument DIRNAME specifies the
visited directory, the argument NAMES lists the files in the
directory (gotten from `posix.listdir(DIRNAME)'). The VISIT
function may modify NAMES to influence the set of directories
visited below DIRNAME, e.g., to avoid visiting certain parts of
the tree. (The object referred to by NAMES must be modified in
place, using `del' or slice assignment.)
File: python-lib.info, Node: pwd, Next: select, Prev: posixpath, Up: UNIX ONLY
Built-in Module `pwd'
=====================
This module provides access to the UNIX password database. It is
available on all UNIX versions.
Password database entries are reported as 7-tuples containing the
following items from the password database (see `<pwd.h>'), in order:
`pw_name', `pw_passwd', `pw_uid', `pw_gid', `pw_gecos', `pw_dir',
`pw_shell'. The uid and gid items are integers, all others are strings.
An exception is raised if the entry asked for cannot be found.
It defines the following items:
- function of module pwd: getpwuid (UID)
Return the password database entry for the given numeric user ID.
- function of module pwd: getpwnam (NAME)
Return the password database entry for the given user name.
- function of module pwd: getpwall ()
Return a list of all available password database entries, in
arbitrary order.
File: python-lib.info, Node: select, Next: socket, Prev: pwd, Up: UNIX ONLY
Built-in module `select'
========================
This module provides access to the function `select' available in most
UNIX versions. It defines the following:
- exception of module select: error
The exception raised when an error occurs. The accompanying value
is a pair containing the numeric error code from `errno' and the
corresponding string, as would be printed by the C function
`perror()'.
- function of module select: select (IWTD, OWTD, EWTD, TIMEOUT)
This is a straightforward interface to the UNIX `select()' system
call. The first three arguments are lists of `waitable objects':
either integers representing UNIX file descriptors or objects with
a parameterless method named `fileno()' returning such an integer.
The three lists of waitable objects are for input, output and
`exceptional conditions', respectively. Empty lists are allowed.
The optional last argument is a time-out specified as a floating
point number in seconds. When the TIMEOUT argument is omitted the
function blocks until at least one file descriptor is ready. A
time-out value of zero specifies a poll and never blocks.
The return value is a triple of lists of objects that are ready:
subsets of the first three arguments. When the time-out is reached
without a file descriptor becoming ready, three empty lists are
returned.
Amongst the acceptable object types in the lists are Python file
objects (e.g. `sys.stdin', or objects returned by `open()' or
`posix.popen()'), socket objects returned by `socket.socket()',
and the module `stdwin' which happens to define a function
`fileno()' for just this purpose. You may also define a "wrapper"
class yourself, as long as it has an appropriate `fileno()' method
(that really returns a UNIX file descriptor, not just a random
integer).
File: python-lib.info, Node: socket, Next: thread, Prev: select, Up: UNIX ONLY
Built-in Module `socket'
========================
This module provides access to the BSD *socket* interface. It is
available on UNIX systems that support this interface.
For an introduction to socket programming (in C), see the following
papers: *An Introductory 4.3BSD Interprocess Communication Tutorial*,
by Stuart Sechrest and *An Advanced 4.3BSD Interprocess Communication
Tutorial*, by Samuel J. Leffler et al, both in the UNIX Programmer's
Manual, Supplementary Documents 1 (sections PS1:7 and PS1:8). The UNIX
manual pages for the various socket-related system calls also a
valuable source of information on the details of socket semantics.
The Python interface is a straightforward transliteration of the UNIX
system call and library interface for sockets to Python's
object-oriented style: the `socket()' function returns a "socket
object" whose methods implement the various socket system calls.
Parameter types are somewhat higer-level than in the C interface: as
with `read()' and `write()' operations on Python files, buffer
allocation on receive operations is automatic, and buffer length is
implicit on send operations.
Socket addresses are represented as a single string for the `AF_UNIX'
address family and as a pair `(HOST, PORT)' for the `AF_INET' address
family, where HOST is a string representing either a hostname in
Internet domain notation like `'daring.cwi.nl'' or an IP address like
`'100.50.200.5'', and PORT is an integral port number. Other address
families are currently not supported. The address format required by a
particular socket object is automatically selected based on the address
family specified when the socket object was created.
All errors raise exceptions. The normal exceptions for invalid
argument types and out-of-memory conditions can be raised; errors
related to socket or address semantics raise the error `socket.error'.
Non-blocking and asynchronous mode are not supported; see module
`select' for a way to do non-blocking socket I/O.
The module `socket' exports the following constants and functions:
- exception of module socket: error
This exception is raised for socket- or address-related errors.
The accompanying value is either a string telling what went wrong
or a pair `(ERRNO, STRING)' representing an error returned by a
system call, similar to the value accompanying `posix.error'.
- data of module socket: AF_UNIX
- data of module socket: AF_INET
These constants represent the address (and protocol) families,
used for the first argument to `socket()'.
- data of module socket: SOCK_STREAM
- data of module socket: SOCK_DGRAM
These constants represent the socket types, used for the second
argument to `socket()'. (There are other types, but only
`SOCK_STREAM' and `SOCK_DGRAM' appear to be generally useful.)
- function of module socket: gethostbyname (HOSTNAME)
Translate a host name to IP address format. The IP address is
returned as a string, e.g., `'100.50.200.5''. If the host name
is an IP address itself it is returned unchanged.
- function of module socket: getservbyname (SERVICENAME, PROTOCOLNAME)
Translate an Internet service name and protocol name to a port
number for that service. The protocol name should be `'tcp'' or
`'udp''.
- function of module socket: socket (FAMILY, TYPE, PROTO)
Create a new socket using the given address family, socket type and
protocol number. The address family should be `AF_INET' or
`AF_UNIX'. The socket type should be `SOCK_STREAM', `SOCK_DGRAM'
or perhaps one of the other `SOCK_' constants. The protocol
number is usually zero and may be omitted in that case.
- function of module socket: fromfd (FD, FAMILY, TYPE, PROTO)
Build a socket object from an existing file descriptor (an integer
as returned by a file object's `fileno' method). Address family,
socket type and protocol number are as for the `socket' function
above. The file descriptor should refer to a socket, but this is
not checked -- subsequent operations on the object may fail if the
file descriptor is invalid. This function is rarely needed, but
can be used to get or set socket options on a socket passed to a
program as standard input or output (e.g. a server started by the
UNIX inet daemon).
* Menu:
* Socket Object::
* Socket Example::
File: python-lib.info, Node: Socket Object, Next: Socket Example, Prev: socket, Up: socket
Socket Object Methods
---------------------
Socket objects have the following methods. Except for `makefile()'
these correspond to UNIX system calls applicable to sockets.
- Method on socket: accept ()
Accept a connection. The socket must be bound to an address and
listening for connections. The return value is a pair `(CONN,
ADDRESS)' where CONN is a *new* socket object usable to send and
receive data on the connection, and ADDRESS is the address bound
to the socket on the other end of the connection.
- Method on socket: bind (ADDRESS)
Bind the socket to an address. The socket must not already be
bound.
- Method on socket: close ()
Close the socket. All future operations on the socket object will
fail. The remote end will receive no more data (after queued data
is flushed). Sockets are automatically closed when they are
garbage-collected.
- Method on socket: connect (ADDRESS)
Connect to a remote socket.
- Method on socket: fileno ()
Return the socket's file descriptor (a small integer). This is
useful with `select'.
- Method on socket: getpeername ()
Return the remote address to which the socket is connected. This
is useful to find out the port number of a remote IP socket, for
instance.
- Method on socket: getsockname ()
Return the socket's own address. This is useful to find out the
port number of an IP socket, for instance.
- Method on socket: getsockopt (LEVEL, OPTNAME, BUFLEN)
Return the value of the given socket option (see the UNIX man page
getsockopt(2)). The needed symbolic constants are defined in
module SOCKET. If the optional third argument is absent, an
integer option is assumed and its integer value is returned by the
function. If BUFLEN is present, it specifies the maximum length
of the buffer used to receive the option in, and this buffer is
returned as a string. It's up to the caller to decode the
contents of the buffer (see the optional built-in module `struct'
for a way to decode C structures encoded as strings).
- Method on socket: listen (BACKLOG)
Listen for connections made to the socket. The argument (in the
range 0-5) specifies the maximum number of queued connections.
- Method on socket: makefile (MODE)
Return a "file object" associated with the socket. (File objects
were described earlier under Built-in Types.) The file object
references a `dup'ped version of the socket file descriptor, so
the file object and socket object may be closed or
garbage-collected independently.
- Method on socket: recv (BUFSIZE, FLAGS)
Receive data from the socket. The return value is a string
representing the data received. The maximum amount of data to be
received at once is specified by BUFSIZE. See the UNIX manual page
for the meaning of the optional argument FLAGS; it defaults to
zero.
- Method on socket: recvfrom (BUFSIZE)
Receive data from the socket. The return value is a pair
`(STRING, ADDRESS)' where STRING is a string representing the data
received and ADDRESS is the address of the socket sending the data.
- Method on socket: send (STRING)
Send data to the socket. The socket must be connected to a remote
socket.
- Method on socket: sendto (STRING, ADDRESS)
Send data to the socket. The socket should not be connected to a
remote socket, since the destination socket is specified by
`address'.
- Method on socket: setsockopt (LEVEL, OPTNAME, VALUE)
Set the value of the given socket option (see the UNIX man page
setsockopt(2)). The needed symbolic constants are defined in
module `SOCKET'. The value can be an integer or a string
representing a buffer. In the latter case it is up to the caller
to ensure that the string contains the proper bits (see the
optional built-in module `struct' for a way to encode C structures
as strings).
- Method on socket: shutdown (HOW)
Shut down one or both halves of the connection. If HOW is `0',
further receives are disallowed. If HOW is `1', further sends are
disallowed. If HOW is `2', further sends and receives are
disallowed.
Note that there are no methods `read()' or `write()'; use `recv()' and
`send()' without FLAGS argument instead.
File: python-lib.info, Node: Socket Example, Prev: Socket Object, Up: socket
Example
-------
Here are two minimal example programs using the TCP/IP protocol: a
server that echoes all data that it receives back (servicing only one
client), and a client using it. Note that a server must perform the
sequence `socket', `bind', `listen', `accept' (possibly repeating the
`accept' to service more than one client), while a client only needs
the sequence `socket', `connect'. Also note that the server does not
`send'/`receive' on the socket it is listening on but on the new socket
returned by `accept'.
# Echo server program
from socket import *
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged server
s = socket(AF_INET, SOCK_STREAM)
s.bind(HOST, PORT)
s.listen(0)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
# Echo client program
from socket import *
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket(AF_INET, SOCK_STREAM)
s.connect(HOST, PORT)
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', `data`
File: python-lib.info, Node: thread, Prev: socket, Up: UNIX ONLY
Built-in Module `thread'
========================
This module provides low-level primitives for working with multiple
threads (a.k.a. "light-weight processes" or "tasks") -- multiple
threads of control sharing their global data space. For
synchronization, simple locks (a.k.a. "mutexes" or "binary semaphores")
are provided.
The module is optional and supported on SGI and Sun Sparc systems only.
It defines the following constant and functions:
- exception of module thread: error
Raised on thread-specific errors.
- function of module thread: start_new_thread (FUNC, ARG)
Start a new thread. The thread executes the function FUNC with
the argument list ARG (which must be a tuple). When the function
returns, the thread silently exits. When the function raises
terminates with an unhandled exception, a stack trace is printed
and then the thread exits (but other threads continue to run).
- function of module thread: exit_thread ()
Exit the current thread silently. Other threads continue to run.
*Caveat:* code in pending `finally' clauses is not executed.
- function of module thread: exit_prog (STATUS)
Exit all threads and report the value of the integer argument
STATUS as the exit status of the entire program. *Caveat:* code
in pending `finally' clauses, in this thread or in other threads,
is not executed.
- function of module thread: allocate_lock ()
Return a new lock object. Methods of locks are described below.
The lock is initially unlocked.
Lock objects have the following methods:
- Method on lock: acquire (WAITFLAG)
Without the optional argument, this method acquires the lock
unconditionally, if necessary waiting until it is released by
another thread (only one thread at a time can acquire a lock --
that's their reason for existence), and returns `None'. If the
integer WAITFLAG argument is present, the action depends on its
value: if it is zero, the lock is only acquired if it can be
acquired immediately without waiting, while if it is nonzero, the
lock is acquired unconditionally as before. If an argument is
present, the return value is 1 if the lock is acquired
successfully, 0 if not.
- Method on lock: release ()
Releases the lock. The lock must have been acquired earlier, but
not necessarily by the same thread.
- Method on lock: locked ()
Return the status of the lock: 1 if it has been acquired by some
thread, 0 if not.
Caveats:
* Threads interact strangely with interrupts: the
`KeyboardInterrupt' exception will be received by an arbitrary
thread.
* Calling `sys.exit(STATUS)' or executing `raise SystemExit, STATUS'
is almost equivalent to calling `thread.exit_prog(STATUS)', except
that the former ways of exiting the entire program do honor
`finally' clauses in the current thread (but not in other threads).
* Not all built-in functions that may block waiting for I/O allow
other threads to run, although the most popular ones (`sleep',
`read', `select') work as expected.
File: python-lib.info, Node: MULTIMEDIA EXTENSIONS, Next: CRYPTOGRAPHIC EXTENSIONS, Prev: UNIX ONLY, Up: Top
MULTIMEDIA EXTENSIONS
*********************
The modules described in this chapter implement various algorithms that
are mainly useful for multimedia applications. They are available at
the discretion of the installation.
* Menu:
* audioop::
* imageop::
* jpeg::
* rgbimg::
File: python-lib.info, Node: audioop, Next: imageop, Prev: MULTIMEDIA EXTENSIONS, Up: MULTIMEDIA EXTENSIONS
Built-in module `audioop'
=========================
The audioop module contains some useful operations on sound fragments.
It operates on sound fragments consisting of signed integer samples of
8, 16 or 32 bits wide, stored in Python strings. This is the same
format as used by the `al' and `sunaudiodev' modules. All scalar items
are integers, unless specified otherwise.
A few of the more complicated operations only take 16-bit samples,
otherwise the sample size (in bytes) is always a parameter of the
operation.
The module defines the following variables and functions:
- exception of module audioop: error
This exception is raised on all errors, such as unknown number of
bytes per sample, etc.
- function of module audioop: add (FRAGMENT1, FRAGMENT2, WIDTH)
This function returns a fragment that is the addition of the two
samples passed as parameters. WIDTH is the sample width in bytes,
either `1', `2' or `4'. Both fragments should have the same length.
- function of module audioop: adpcm2lin (ADPCMFRAGMENT, WIDTH, STATE)
This routine decodes an Intel/DVI ADPCM coded fragment to a linear
fragment. See the description of `lin2adpcm' for details on ADPCM
coding. The routine returns a tuple `(SAMPLE, NEWSTATE)' where the
sample has the width specified in WIDTH.
- function of module audioop: adpcm32lin (ADPCMFRAGMENT, WIDTH, STATE)
This routine decodes an alternative 3-bit ADPCM code. See
`lin2adpcm3' for details.
- function of module audioop: avg (FRAGMENT, WIDTH)
This function returns the average over all samples in the fragment.
- function of module audioop: avgpp (FRAGMENT, WIDTH)
This function returns the average peak-peak value over all samples
in the fragment. No filtering is done, so the useability of this
routine is questionable.
- function of module audioop: bias (FRAGMENT, WIDTH, BIAS)
This function returns a fragment that is the original fragment
with a bias added to each sample.
- function of module audioop: cross (FRAGMENT, WIDTH)
This function returns the number of zero crossings in the fragment
passed as an argument.
- function of module audioop: findfactor (FRAGMENT, REFERENCE)
This routine (which only accepts 2-byte sample fragments)
calculates a factor F such that `rms(add(fragment, mul(reference,
-F)))' is minimal, i.e. it calculates the factor with which you
should multiply REFERENCE to make it match as good as possible to
FRAGMENT. The fragments should be the same size.
The time taken by this routine is proportional to `len(fragment)'.
- function of module audioop: findfit (FRAGMENT, REFERENCE)
This routine (which only accepts 2-byte sample fragments) tries to
match REFERENCE as good as possible to a portion of FRAGMENT
(which should be the longer fragment). It (conceptually) does this
by taking slices out of FRAGMENT, using `findfactor' to compute
the best match, and minimizing the result. It returns a tuple
`(OFFSET, FACTOR)' with offset the (integer) offset into FRAGMENT
where the optimal match started and FACTOR the floating-point
factor as per findfactor.
- function of module audioop: findmax (FRAGMENT, LENGTH)
This routine (which only accepts 2-byte sample fragments) searches
FRAGMENT for a slice of length LENGTH samples (not bytes!) with
maximum energy, i.e. it returns I for which
`rms(fragment[i*2:(i+length)*2])' is maximal.
The routine takes time proportional to `len(fragment)'.
- function of module audioop: getsample (FRAGMENT, WIDTH, INDEX)
This function returns the value of sample INDEX from the fragment.
- function of module audioop: lin2lin (FRAGMENT, WIDTH, NEWWIDTH)
This function converts samples between 1-, 2- and 4-byte formats.
- function of module audioop: lin2adpcm (FRAGMENT, WIDTH, STATE)
This function converts samples to 4 bit Intel/DVI ADPCM encoding.
ADPCM coding is an adaptive coding scheme, whereby each 4 bit
number is the difference between one sample and the next, divided
by a (varying) step. The Intel/DVI ADPCM algorythm has been
selected for use by the IMA, so may well become a standard.
`State' is a tuple containing the state of the coder. The coder
returns a tuple `(ADPCMFRAG, NEWSTATE)', and the NEWSTATE should
be passed to the next call of lin2adpcm. In the initial call
`None' can be passed as the state. ADPCMFRAG is the ADPCM coded
fragment packed 2 4-bit values per byte.
- function of module audioop: lin2adpcm3 (FRAGMENT, WIDTH, STATE)
This is an alternative ADPCM coder that uses only 3 bits per
sample. It is not compatible with the Intel/DVI ADPCM coder and
its output is not packed (due to laziness on the side of the
author). Its use is discouraged.
- function of module audioop: lin2ulaw (FRAGMENT, WIDTH)
This function converts samples in the audio fragment to U-LAW
encoding and returns this as a python string. U-LAW is an audio
encoding format whereby you get a dynamic range of about 14 bits
using only 8 bit samples. It is used by the Sun audio hardware,
among others.
- function of module audioop: minmax (FRAGMENT, WIDTH)
This function returns a tuple consisting of the minimum and maximum
values of all samples in the sound fragment.
- function of module audioop: max (FRAGMENT, WIDTH)
This function returns the maximum of the *absolute value* of all
samples in a fragment.
- function of module audioop: maxpp (FRAGMENT, WIDTH)
This function returns the maximum peak-peak value in the sound
fragment.
- function of module audioop: mul (FRAGMENT, WIDTH, FACTOR)
Mul returns a fragment that has all samples in the original
framgent multiplied by the floating-point value FACTOR. Overflow is
silently ignored.
- function of module audioop: reverse (FRAGMENT, WIDTH)
This function reverses the samples in a fragment and returns the
modified fragment.
- function of module audioop: tomono (FRAGMENT, WIDTH, LFACTOR,
RFACTOR)
This function converts a stereo fragment to a mono fragment. The
left channel is multiplied by LFACTOR and the right channel by
RFACTOR before adding the two channels to give a mono signal.
- function of module audioop: tostereo (FRAGMENT, WIDTH, LFACTOR,
RFACTOR)
This function generates a stereo fragment from a mono fragment.
Each pair of samples in the stereo fragment are computed from the
mono sample, whereby left channel samples are multiplied by LFACTOR
and right channel samples by RFACTOR.
- function of module audioop: mul (FRAGMENT, WIDTH, FACTOR)
Mul returns a fragment that has all samples in the original
framgent multiplied by the floating-point value FACTOR. Overflow is
silently ignored.
- function of module audioop: rms (FRAGMENT, WIDTH, FACTOR)
Returns the root-mean-square of the fragment, i.e. the square
root of the quotient of the sum of all squared sample value,
divided by the sumber of samples. This is a measure of the power
in an audio signal.
- function of module audioop: ulaw2lin (FRAGMENT, WIDTH)
This function converts sound fragments in ULAW encoding to linearly
encoded sound fragments. ULAW encoding always uses 8 bits samples,
so WIDTH refers only to the sample width of the output fragment
here.
Note that operations such as `mul' or `max' make no distinction between
mono and stereo fragments, i.e. all samples are treated equal. If this
is a problem the stereo fragment should be split into two mono
fragments first and recombined later. Here is an example of how to do
that:
def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
lsample = audioop.mul(sample, width, lfactor)
rsample = audioop.mul(sample, width, rfactor)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
If you use the ADPCM coder to build network packets and you want your
protocol to be stateless (i.e. to be able to tolerate packet loss) you
should not only transmit the data but also the state. Note that you
should send the INITIAL state (the one you passed to lin2adpcm) along
to the decoder, not the final state (as returned by the coder). If you
want to use `struct' to store the state in binary you can code the
first element (the predicted value) in 16 bits and the second (the
delta index) in 8.
The ADPCM coders have never been tried against other ADPCM coders, only
against themselves. It could well be that I misinterpreted the
standards in which case they will not be interoperable with the
respective standards.
The `find...' routines might look a bit funny at first sight. They are
primarily meant for doing echo cancellation. A reasonably fast way to
do this is to pick the most energetic piece of the output sample,
locate that in the input sample and subtract the whole output sample
from the input sample:
def echocancel(outputdata, inputdata):
pos = audioop.findmax(outputdata, 800) # one tenth second
out_test = outputdata[pos*2:]
in_test = inputdata[pos*2:]
ipos, factor = audioop.findfit(in_test, out_test)
# Optional (for better cancellation):
# factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
# out_test)
prefill = '\0'*(pos+ipos)*2
postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
outputdata = prefill + audioop.mul(outputdata,2,-factor) + postfill
return audioop.add(inputdata, outputdata, 2)
File: python-lib.info, Node: imageop, Next: jpeg, Prev: audioop, Up: MULTIMEDIA EXTENSIONS
Built-in module `imageop'
=========================
The imageop module contains some useful operations on images. It
operates on images consisting of 8 or 32 bit pixels stored in python
strings. This is the same format as used by `gl.lrectwrite' and the
`imgfile' module.
The module defines the following variables and functions:
- exception of module imageop: error
This exception is raised on all errors, such as unknown number of
bits per pixel, etc.
- function of module imageop: crop (IMAGE, PSIZE, WIDTH, HEIGHT, X0,
Y0, X1, Y1)
This function takes the image in `image', which should by `width'
by `height' in size and consist of pixels of `psize' bytes, and
returns the selected part of that image. `X0', `y0', `x1' and `y1'
are like the `lrectread' parameters, i.e. the boundary is included
in the new image. The new boundaries need not be inside the
picture. Pixels that fall outside the old image will have their
value set to zero. If `x0' is bigger than `x1' the new image is
mirrored. The same holds for the y coordinates.
- function of module imageop: scale (IMAGE, PSIZE, WIDTH, HEIGHT,
NEWWIDTH, NEWHEIGHT)
This function returns a `image' scaled to size `newwidth' by
`newheight'. No interpolation is done, scaling is done by
simple-minded pixel duplication or removal. Therefore,
computer-generated images or dithered images will not look nice
after scaling.
- function of module imageop: tovideo (IMAGE, PSIZE, WIDTH, HEIGHT)
This function runs a vertical low-pass filter over an image. It
does so by computing each destination pixel as the average of two
vertically-aligned source pixels. The main use of this routine is
to forestall excessive flicker if the image is displayed on a video
device that uses interlacing, hence the name.
- function of module imageop: grey2mono (IMAGE, WIDTH, HEIGHT,
THRESHOLD)
This function converts a 8-bit deep greyscale image to a 1-bit deep
image by tresholding all the pixels. The resulting image is tightly
packed and is probably only useful as an argument to `mono2grey'.
- function of module imageop: dither2mono (IMAGE, WIDTH, HEIGHT)
This function also converts an 8-bit greyscale image to a 1-bit
monochrome image but it uses a (simple-minded) dithering algorithm.
- function of module imageop: mono2grey (IMAGE, WIDTH, HEIGHT, P0, P1)
This function converts a 1-bit monochrome image to an 8 bit
greyscale or color image. All pixels that are zero-valued on input
get value `p0' on output and all one-value input pixels get value
`p1' on output. To convert a monochrome black-and-white image to
greyscale pass the values `0' and `255' respectively.
- function of module imageop: grey2grey4 (IMAGE, WIDTH, HEIGHT)
Convert an 8-bit greyscale image to a 4-bit greyscale image without
dithering.
- function of module imageop: grey2grey2 (IMAGE, WIDTH, HEIGHT)
Convert an 8-bit greyscale image to a 2-bit greyscale image without
dithering.
- function of module imageop: dither2grey2 (IMAGE, WIDTH, HEIGHT)
Convert an 8-bit greyscale image to a 2-bit greyscale image with
dithering. As for `dither2mono', the dithering algorithm is
currently very simple.
- function of module imageop: grey42grey (IMAGE, WIDTH, HEIGHT)
Convert a 4-bit greyscale image to an 8-bit greyscale image.
- function of module imageop: grey22grey (IMAGE, WIDTH, HEIGHT)
Convert a 2-bit greyscale image to an 8-bit greyscale image.
File: python-lib.info, Node: jpeg, Next: rgbimg, Prev: imageop, Up: MULTIMEDIA EXTENSIONS
Built-in Module `jpeg'
======================
The module jpeg provides access to the jpeg compressor and decompressor
written by the Independent JPEG Group. JPEG is a (draft?) standard for
compressing pictures. For details on jpeg or the Indepent JPEG Group
software refer to the JPEG standard or the documentation provided with
the software.
The jpeg module defines these functions:
- function of module jpeg: compress (DATA, W, H, B)
Treat data as a pixmap of width w and height h, with b bytes per
pixel. The data is in sgi gl order, so the first pixel is in the
lower-left corner. This means that lrectread return data can
immedeately be passed to compress. Currently only 1 byte and 4
byte pixels are allowed, the former being treaded as greyscale and
the latter as RGB color. Compress returns a string that contains
the compressed picture, in JFIF format.
- function of module jpeg: decompress (DATA)
Data is a string containing a picture in JFIF format. It returns a
tuple `(DATA, WIDTH, HEIGHT, BYTESPERPIXEL)'. Again, the data is
suitable to pass to lrectwrite.
- function of module jpeg: setoption (NAME, VALUE)
Set various options. Subsequent compress and decompress calls
will use these options. The following options are available:
`'forcegray''
Force output to be grayscale, even if input is RGB.
`'quality''
Set the quality of the compressed image to a value between
`0' and `100' (default is `75'). Compress only.
`'optimize''
Perform huffman table optimization. Takes longer, but
results in smaller compressed image. Compress only.
`'smooth''
Perform inter-block smoothing on uncompressed image. Only
useful for low-quality images. Decompress only.
Compress and uncompress raise the error jpeg.error in case of errors.
File: python-lib.info, Node: rgbimg, Prev: jpeg, Up: MULTIMEDIA EXTENSIONS
Built-in module `rgbimg'
========================
The rgbimg module allows python programs to access SGI imglib image
files (also known as `.rgb' files). The module is far from complete,
but is provided anyway since the functionality that there is is enough
in some cases. Currently, colormap files are not supported.
The module defines the following variables and functions:
- exception of module rgbimg: error
This exception is raised on all errors, such as unsupported file
type, etc.
- function of module rgbimg: sizeofimage (FILE)
This function returns a tuple `(X, Y)' where X and Y are the size
of the image in pixels. Only 4 byte RGBA pixels, 3 byte RGB
pixels, and 1 byte greyscale pixels are currently supported.
- function of module rgbimg: longimagedata (FILE)
This function reads and decodes the image on the specified file,
and returns it as a python string. The string has 4 byte RGBA
pixels. The bottom left pixel is the first in the string. This
format is suitable to pass to `gl.lrectwrite', for instance.
- function of module rgbimg: longstoimage (DATA, X, Y, Z, FILE)
This function writes the RGBA data in DATA to image file FILE. X
and Y give the size of the image. Z is 1 if the saved image
should be 1 byte greyscale, 3 if the saved image should be 3 byte
RGB data, or 4 if the saved images should be 4 byte RGBA data.
The input data always contains 4 bytes per pixel. These are the
formats returned by `gl.lrectread'.
- function of module rgbimg: ttob (FLAG)
This function sets a global flag which defines whether the scan
lines of the image are read or written from bottom to top (flag is
zero, compatible with SGI GL) or from top to bottom(flag is one,
compatible with X). The default is zero.
File: python-lib.info, Node: CRYPTOGRAPHIC EXTENSIONS, Next: STDWIN ONLY, Prev: MULTIMEDIA EXTENSIONS, Up: Top
CRYPTOGRAPHIC EXTENSIONS
************************
The modules described in this chapter implement various algorithms of a
cryptographic nature. They are available at the discretion of the
installation.
* Menu:
* md5::
* mpz::
* rotor::
File: python-lib.info, Node: md5, Next: mpz, Prev: CRYPTOGRAPHIC EXTENSIONS, Up: CRYPTOGRAPHIC EXTENSIONS
Built-in module `md5'
=====================
This module implements the interface to RSA's MD5 message digest
algorithm (see also the file `md5.doc'). It's use is very
straightforward: use the function `md5' to create an "md5"-object. You
can now "feed" this object with arbitrary strings.
At any time you can ask the "final" digest of the object. Internally, a
temorary copy of the object is made and the digest is computed and
returned. Because of the copy, the digest operation is not desctructive
for the object. Before a more exact description of the use, a small
example: to obtain the digest of the string `'abc'', use ...
>>> from md5 import md5
>>> m = md5()
>>> m.update('abc')
>>> m.digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r'
More condensed:
>>> md5('abc').digest()
'\220\001P\230<\322O\260\326\226?}(\341\177r'
- function of module md5: md5 (ARG)
Create a new md5-object. ARG is optional: if present, an initial
`update' method is called with ARG as argument.
An md5-object has the following methods:
- Method on md5: update (ARG)
Update this md5-object with the string ARG.
- Method on md5: digest ()
Return the "digest" of this md5-object. Internally, a copy is made
and the C-function `MD5Final' is called. Finally the digest is
returned.
- Method on md5: copy ()
Return a separate copy of this md5-object. An `update' to this
copy won't affect the original object.
File: python-lib.info, Node: mpz, Next: rotor, Prev: md5, Up: CRYPTOGRAPHIC EXTENSIONS
Built-in module `mpz'
=====================
This module implements the interface to part of the GNU MP library.
This library contains arbitrary precision integer and rational number
arithmetic routines. Only the interfaces to the *integer* (`mpz_...')
routines are provided. If not stated otherwise, the description in the
GNU MP documentation can be applied.
In general, "mpz"-numbers can be used just like other standard Python
numbers, e.g. you can use the built-in operators like `+', `*', etc.,
as well as the standard built-in functions like `abs', `int', ...,
`divmod', `pow'. *Please note:* the bitwise-xor operation has been
implemented as a bunch of ands, inverts and ors, because the library
lacks an `mpz_xor' function, and I didn't need one.
You create an mpz-number, by calling the function called `mpz' (see
below for an excact description). An mpz-number is printed like this:
`mpz(VALUE)'.
- function of module mpz: mpz (VALUE)
Create a new mpz-number. VALUE can be an integer, a long, another
mpz-number, or even a string. If it is a string, it is interpreted
as an array of radix-256 digits, least significant digit first,
resulting in a positive number. See also the `binary' method,
described below.
A number of *extra* functions are defined in this module. Non
mpz-arguments are converted to mpz-values first, and the functions
return mpz-numbers.
- function of module mpz: powm (BASE, EXPONENT, MODULUS)
Return `pow(BASE, EXPONENT) % MODULUS'. If `EXPONENT == 0', return
`mpz(1)'. In contrast to the C-library function, this version can
handle negative exponents.
- function of module mpz: gcd (OP1, OP2)
Return the greatest common divisor of OP1 and OP2.
- function of module mpz: gcdext (A, B)
Return a tuple `(G, S, T)', such that `A*S + B*T == G == gcd(A,
B)'.
- function of module mpz: sqrt (OP)
Return the square root of OP. The result is rounded towards zero.
- function of module mpz: sqrtrem (OP)
Return a tuple `(ROOT, REMAINDER)', such that `ROOT*ROOT +
REMAINDER == OP'.
- function of module mpz: divm (NUMERATOR, DENOMINATOR, MODULUS)
Returns a number Q. such that `Q * DENOMINATOR % MODULUS ==
NUMERATOR'. One could also implement this function in python,
using `gcdext'.
An mpz-number has one method:
- Method on mpz: binary ()
Convert this mpz-number to a binary string, where the number has
been stored as an array of radix-256 digits, least significant
digit first.
The mpz-number must have a value greater than- or equal to zero,
otherwise a `ValueError'-exception will be raised.
File: python-lib.info, Node: rotor, Prev: mpz, Up: CRYPTOGRAPHIC EXTENSIONS
Built-in module `rotor'
=======================
This module implements a rotor-based encryption algorithm, contributed
by Lance Ellinghouse. Currently no further documentation is available
-- you are kindly advised to read the source...
File: python-lib.info, Node: STDWIN ONLY, Next: SGI IRIX ONLY, Prev: CRYPTOGRAPHIC EXTENSIONS, Up: Top
STDWIN ONLY
***********
* Menu:
* stdwin::
* stdwinevents::
* rect::
File: python-lib.info, Node: stdwin, Next: stdwinevents, Prev: STDWIN ONLY, Up: STDWIN ONLY
Built-in Module `stdwin'
========================
This module defines several new object types and functions that provide
access to the functionality of the Standard Window System Interface,
STDWIN [CWI report CR-R8817]. It is available on systems to which
STDWIN has been ported (which is most systems). It is only available
if the `DISPLAY' environment variable is set or an explicit `-display
DISPLAYNAME' argument is passed to the interpreter.
Functions have names that usually resemble their C STDWIN counterparts
with the initial `w' dropped. Points are represented by pairs of
integers; rectangles by pairs of points. For a complete description of
STDWIN please refer to the documentation of STDWIN for C programmers
(aforementioned CWI report).
* Menu:
* Functions Defined in Module stdwin::
* Window Object::
* Drawing Object::
* Menu Object::
* Bitmap Object::
* Text-edit Object::
* Stdwin Example::